#include "udiskmanager.h"
#include "qterminal.h"
#include "_def_p.h"
#include <QStringList>

QStringList UdiskManager::enumDevices()
{
    QStringList devices;

    bool ret = true;
    QString message;
    QTerminal terminal;
    ret = ret && terminal.run("lsblk -e7 -e11 -nl | awk '{printf $1 \" \" $3 \"\\n\"}' | grep '\\s1$' | awk '{print $1}' | grep -E 's[a-zA-Z]{2}[0-9]$'", &message);
    if (ret)
    {
        QStringList parts = message.split("\n", QString::SkipEmptyParts);
        foreach (const QString &part, parts)
        {
            devices << QString("/dev/%1").arg(part);
        }
    }

    return devices;
}

bool UdiskManager::mount(const QString &device, const QString &dir, QString *message)
{
    bool ret = true;
    QTerminal terminal(TOKEN);
    QString mountDir = toNormalizedPath(dir);
    ret = ret && terminal.run(QString("mkdir -p %1").arg(mountDir), message);
    ret = ret && terminal.runAsAdmin(QString("mount %1 %2 -o uid=1000,gid=1000,rw,noexec").arg(device).arg(mountDir), message);
    return ret;
}

bool UdiskManager::umount(const QString &device, QString *message)
{
    bool ret = true;
    QTerminal terminal(TOKEN);
    QString mountDir = isDir(device) ? toNormalizedPath(device) : device;
    ret = ret && terminal.runAsAdmin(QString("umount %1 -A").arg(mountDir), message);
    if (!ret)
    {
        terminal.runAsAdmin(QString("fuser -umv -k %1").arg(mountDir), message);
        ret = terminal.runAsAdmin(QString("umount %1 -A -l -f").arg(mountDir), message);
    }

    return ret;
}

bool UdiskManager::isMount(const QString &device, const QString &dir, QString *message)
{
    bool ret = true;
    QTerminal terminal;
    QString mountDir = dir.isEmpty() ? dir : toNormalizedPath(dir);
    QString cmd = QString("mount | grep '%1 on %2'").arg(device).arg(mountDir);
    ret = ret && terminal.run(cmd, message);
    return ret;
}

bool UdiskManager::isMountDirReadOnly(const QString &device, const QString &dir, QString *message)
{
    bool ret = true;
    QTerminal terminal;
    QString cmd = QString("mount | grep '%1 on %2 type \\w* (ro'").arg(device).arg(toNormalizedPath(dir));
    ret = ret && terminal.run(cmd, message);
    return ret;
}

bool UdiskManager::isMountDirWritable(const QString &device, const QString &dir, QString *message)
{
    bool ret = true;
    QTerminal terminal;
    QString cmd = QString("mount | grep '%1 on %2 type \\w* (rw'").arg(device).arg(toNormalizedPath(dir));
    ret = ret && terminal.run(cmd, message);
    return ret;
}
